package cn.com.utt.gateway.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;

/**
 * 单数据源配置
 */
@Configuration
@MapperScan(basePackages = "cn.com.crm.unms.mapper", sqlSessionTemplateRef = "crmSqlSessionTemplate")
public class CrmDataSourceConfiguration {

	@Bean
    @ConfigurationProperties(prefix = "crm.jdbc.ds")
    public DataSource crmReadDataSource() {
        return new DruidDataSource();
    }
    
    @Bean
    public SqlSessionFactory crmSqlSessionFactory(@Qualifier("crmReadDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
    
    @Bean
    public DataSourceTransactionManager crmTransactionManager(@Qualifier("crmReadDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate crmSqlSessionTemplate(@Qualifier("crmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}